package com.xishu.aop;

import com.xishu.config.Config;
import com.xishu.config.Constant;
import com.xishu.util.MongoId;
import com.xishu.util.ServletUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.ThreadContext;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Configuration
@WebFilter(filterName = "userfilter", urlPatterns = "/*")
public class UserFilter implements Filter {
    private static Logger logger = LoggerFactory.getLogger(UserFilter.class);


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        addCrossDomain();
        ThreadContext.put(Constant.REQUEST_ID, MongoId.generateId());
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        logger.info("url is {} begin", request.getRequestURL());

        if (request.getRequestURI().equals("/.well-known/apple-developer-merchantid-domain-association")) {

            //直接返回文件内容
            String filePath = Constant.RESOURCE_PATH + "/apple-developer-merchantid-domain-association";
            File file = new File(filePath);
            FileInputStream fileInputStream = new FileInputStream(file);

            try {
                logger.info("will response the file");
                IOUtils.copy(fileInputStream, servletResponse.getOutputStream());
                return;
            } finally {
                IOUtils.closeQuietly(fileInputStream);
                IOUtils.closeQuietly(servletResponse.getOutputStream());
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);
        logger.info("url is {} end", request.getRequestURL());
    }

    @Override
    public void destroy() {

    }

    private void addCrossDomain() {
        Config config = Config.getInstance();
        logger.info("in cross domain");
        if (config.isAliyun()) {
            logger.info("send cross domain");
            HttpServletRequest httpServletRequest = ServletUtil.getRequest();
            HttpServletResponse httpServletResponse = ServletUtil.getResponse();
            String originHeader = httpServletRequest.getHeader("Origin");
            if (StringUtils.isEmpty(originHeader)) originHeader = "*";
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            httpServletResponse.setHeader("Access-Control-Expose-Headers", Constant.SESSION_TOKEN);
        }
    }


}
